//
//  QMainChargeBookVC.m
//  QoilPublic
//
//  Created by 杨凯 on 16/9/6.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QMainChargeBookVC.h"
#import "QMainChargeBookView.h"
#import "QChargeBookDB.h"
#import "QChargeBookCell.h"
#import "QChargeBookVC.h"
#import "QEditChargeBookVC.h"
#import "QMainChargeBookNoDataView.h"
@interface QMainChargeBookVC ()<UITableViewDataSource,UITableViewDelegate>

@end

@implementation QMainChargeBookVC{

    UITableView *_tableView;
    QMainChargeBookNoDataView *_nodataView;
    NSMutableArray *_allData;
    QChargeBookCell *_chargeCell;
    QMainChargeBookView *headView;
    NSMutableArray *sArr;//过虑变动的的年月
    NSMutableArray *allArr;
    int uploadCount;
}

- (void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"记账本";
    self.automaticallyAdjustsScrollViewInsets = NO;

     sArr = [NSMutableArray array];
     _allData = [NSMutableArray array];
    [self requestFileData];

   
    [self createUI];
    [self notiAction];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiAction) name:kNotificationShowData object:nil];
}

#pragma mark --- 数据
- (void)notiAction{
    [_allData removeAllObjects];
    NSDateFormatter *datefot = [[NSDateFormatter alloc] init];
    datefot.dateFormat = @"YYYYMM";
    NSString *str = [datefot stringFromDate:[NSDate date]];
    
    NSArray *arr = [QChargeBookDB queryMainPageData:str];//取最近三条数据
    _allData = [QChargeBookDB setupChargeBookData:arr];
    [_tableView reloadData];
    
    NSArray *monthArr = [QChargeBookDB queryMainPageWithMonthData:str];//一个月的数据
    NSArray *data = [QChargeBookDB setupChargeBookData:monthArr];
    if(data.count){
        headView.haveData = YES;
        headView.data = data[0];
        _nodataView.hidden = YES;
    }else{
        headView.haveData = NO;
        _nodataView.hidden = NO;

    }
}

- (void)createUI{
    CGFloat h = 0.0;
    if(iphone4x_3_5){
        h = 170;
    }else if (iphone5x_4_0){
        h = 180;
    }else if (iphone6_4_7){
        h = 200;
    }else if (iphone6Plus_5_5){
        h = 230;
    }
    headView = [[[NSBundle mainBundle] loadNibNamed:@"QMainChargeBookView" owner:self options:nil] lastObject];
    headView.frame = CGRectMake(0, kNavHeight+kStatusHeight, kScreenWidth, h);
    [self.view addSubview:headView];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    WS(wSelf);
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headView.mas_bottom);
        make.left.equalTo(headView.mas_left);
        make.right.equalTo(headView.mas_right);
        make.bottom.equalTo(wSelf.view.mas_bottom);
    }];
    
    _nodataView = [[[NSBundle mainBundle] loadNibNamed:@"QMainChargeBookNoDataView" owner:self options:nil] lastObject];
    
    [self.view addSubview:_nodataView];
    [_nodataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headView.mas_bottom);
        make.left.equalTo(headView.mas_left);
        make.right.equalTo(headView.mas_right);
        make.bottom.equalTo(wSelf.view.mas_bottom);
    }];
    
    [_tableView registerNib:[UINib nibWithNibName:@"QChargeBookCell" bundle:nil] forCellReuseIdentifier:@"QChargeBookCell"];
    _chargeCell = [_tableView dequeueReusableCellWithIdentifier:@"QChargeBookCell"];
    
    UIButton *addButton = [QViewUtility createButtonWithFrame:CGRectMake((kScreenWidth-65)/2, kScreenHeight-85, 65, 65) font:18 title:@"" titleColor:[UIColor whiteColor] backgroundColor:[UIColor clearColor]];
    addButton.tag = 1;
    [addButton addTarget:self action:@selector(seeAction:) forControlEvents:UIControlEventTouchUpInside];
    [addButton setBackgroundImage:[UIImage imageNamed:@"add_button"] forState:UIControlStateNormal];
    [self.view addSubview:addButton];
}

#pragma mark --- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _allData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [_allData[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QChargeBookCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QChargeBookCell" forIndexPath:indexPath];
    cell.indexPath = indexPath;
    cell.monthArr = _allData[indexPath.section];
    cell.model =  _allData[indexPath.section][indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 50;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(15.5,2, 10, 10)];
    imgV.backgroundColor = [UIColor grayColor];
    imgV.alpha = 0.5;
    imgV.layer.cornerRadius = 5.0;
    [view addSubview:imgV];
    
    UIButton *button = [QViewUtility createButtonWithFrame:CGRectMake(45,0,90,30) font:14 title:@"查看全部明细" titleColor:[QColorUtility defaultBlueColor] backgroundColor:[UIColor clearColor]];
    button.tag = 2;
    button.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 15,2);
    [button addTarget:self action:@selector(seeAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    return view;
}

- (void)seeAction:(UIButton *)btn{
    if(btn.tag == 1){
        QEditChargeBookVC *vc = [[QEditChargeBookVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (btn.tag == 2){
        QChargeBookVC *vc = [[QChargeBookVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    _chargeCell.indexPath = indexPath;
    _chargeCell.monthArr = _allData[indexPath.section];//一个月的数据
    _chargeCell.model = _allData[indexPath.section][indexPath.row];
    return [_chargeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height+1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *monthArr = _allData[indexPath.section];//一个月的数据
    QChargeBookModel *model = monthArr[indexPath.row];
    QEditChargeBookVC *vc = [[QEditChargeBookVC alloc] init];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

//请求配置文件
- (void)requestFileData{
    NSString *url = [QParamService urlWithAction:@"findBilling"];
    NSDictionary *param = [QParamService updateDatatype:@"2" fileName:@""];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            NSDictionary *dic = basModel.items;
            NSArray *fileList = dic[@"fileList"];
            if(fileList.count){
                NSDictionary *urlDic = fileList[0];
                NSString *url = urlDic[@"url"];
               [self requestDataUrl:url];
            }
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

//请求配置文件数据和本地对比
- (void)requestDataUrl:(NSString *)url{
    NSArray *selfArr;
    [sArr removeAllObjects];
    
    NSString *documentDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *fielDirectory = [documentDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"file%@",[QUserInfo sharedInfo].loginModel.tel]];//文件夹路径
    NSString *filePath = [fielDirectory stringByAppendingPathComponent:@"accountSetting"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:filePath]) {
        selfArr = @[];
    }else{
       selfArr = [QChargeBookDB readDataArrToFilePath:filePath];
    }
    
    [[QHttpManager sharedManager] update:url completion:^(NSData *data, NSArray *arr, NSError *error) {
        if(error){
            return ;
        }
        NSArray *serverArr = arr;
        [sArr addObjectsFromArray:arr];
        if(serverArr.count){
            for (int i=0; i<serverArr.count; ++i){
                NSDictionary *serverDic = serverArr[i];
                NSString *serverfileName = serverDic[@"fileName"];
                NSString *serverTime = serverDic[@"editTime"];
                
                for (int j=0; j<selfArr.count; ++j) {
                    NSDictionary *selfDic = selfArr[j];
                    NSString *selfFileName = selfDic[@"fileName"];
                    NSString *selfTime = selfDic[@"editTime"];
                    
                    if([serverfileName isEqualToString:selfFileName] && [serverTime isEqualToString:selfTime]){
                        [sArr removeObject:serverArr[i]];
                   
                    }
                }
            }
        }
        
        if (![fileManager fileExistsAtPath:filePath]) {
            CLog(@"全部请求");
            if(sArr.count){
                allArr = [NSMutableArray array];
                for(int i=0; i<sArr.count; ++i){
                    NSDictionary *d = sArr[i];
                    NSString *fileName = d[@"fileName"];
                     NSString * yearMonth = [fileName substringWithRange:NSMakeRange(11, 6)];
                    [self updateRequestDataFromServer:url fileName:fileName yearMonth:yearMonth time:d[@"editTime"]];
                }
            }
        }else{
            if(sArr.count){//说明有更新的数据
                allArr = [NSMutableArray array];
                for(int i=0; i<sArr.count; ++i){//先删除要地的要更新的数据
                    NSDictionary *d = sArr[i];
                    NSString *fileName = d[@"fileName"];
                    NSString * yearMonth = [fileName substringWithRange:NSMakeRange(11, 6)];
                    [self updateRequestDataFromServer:url fileName:fileName yearMonth:yearMonth time:d[@"editTime"]];
                }
            }else{
                [self notiAction];
            }
        }
    }];
}

- (void)updateRequestDataFromServer:(NSString *)url fileName:(NSString *)fileName yearMonth:(NSString *)yearMonth time:(NSString *)time{
    NSArray *arr = [url componentsSeparatedByString:@"account"];
    if(arr.count){
        url = arr[0];
        url = [NSString stringWithFormat:@"%@%@",url,fileName];
    }
    [QViewUtility showCustomLoadingToView:self.view hideBg:NO custTitle:@"正在同步" loadType:14];
        [[QHttpManager sharedManager] updateData:url completion:^(NSData *data, NSDictionary *dic, NSError *error) {
            uploadCount++;
            CLog(@"yearMonth========================================%@",yearMonth);
            CLog(@"->>>>>>>>>>%@",dic[@"list"]);
            [allArr addObjectsFromArray:dic[@"list"]];
            [self wreteProfilePath:yearMonth time:time];//写入配置文件
           [QChargeBookDB deleteChargeBookDataWithYearMonth:yearMonth successsBlock:^{
               if(uploadCount == sArr.count){
                   CLog(@"下载完毕下载完毕下载完毕下载完毕下载完毕下载完毕下载完毕下载完毕");
                   [QChargeBookDB saveChargeBookUpdateAllData:allArr successBlock:^{
                       [self notiAction];
                       [QViewUtility hideCustMBHudToView:self.view];
                       [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"同步成功" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
                   }];
               }
        }];
    }];
}

- (void)wreteProfilePath:(NSString *)yearMonth time:(NSString *)time{
    [QChargeBookDB writeProfileByYearMonth:yearMonth time:time successBlock:^(NSString *arrf) {
        CLog(@"写入配置文件成功");
    }];
}

@end
